﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Altairis.FluffyCloud.Data;
using Altairis.FluffyCloud.Security;

namespace Altairis.FluffyCloud.WebCore.Pages.Forum {

    public partial class Detail : DbPage {

        public bool CanDeleteAll { get; set; }

        public bool CanDeleteOwn { get; set; }

        public bool CanEditPosts { get; set; }

        public bool IsBookmarked { get; set; }

        public DateTimeOffset LastVisitDate { get; set; }

        public int TopicId {
            get {
                return int.Parse(this.RouteData.Values["id"] as string);
            }
        }

        public Topic HeaderFormView_GetItem() {
            var t = this.DbContext.Topics.FirstOrDefault(x => x.TopicId == this.TopicId);
            if (t != null) {
                this.Title = t.Name;
                this.CanEditPosts = t.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationEdit);
                this.CanDeleteOwn = t.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationDeleteOwn);
                this.CanDeleteAll = t.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationDeleteAll);
                var s = t.UserStates.SingleOrDefault(x => x.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase));
                this.LastVisitDate = s == null ? DateTimeOffset.MaxValue : s.LastVisitDate;
                this.IsBookmarked = s == null ? false : s.IsBookmarked;
            }
            return t;
        }

        public IQueryable<TopicPost> PostsListView_GetData() {
            var topicId = int.Parse(this.RouteData.Values["id"] as string);
            var q = from p in this.DbContext.TopicPosts
                    where p.TopicId == topicId
                    orderby p.DateCreated descending
                    select p;
            return q;
        }

        protected void HeaderFormView_ItemCommand(object sender, FormViewCommandEventArgs e) {
            if (e.CommandName.Equals("NewPost")) {
                var tb = HeaderFormView.FindControl("NewPostTextBox") as TextBox;
                this.DbContext.TopicPosts.Add(new TopicPost {
                    TopicId = this.TopicId,
                    UserName = this.User.Identity.Name,
                    Text = tb.Text,
                    IpAddress = this.Request.UserHostAddress
                });
                this.DbContext.SaveChanges();
                this.Response.Redirect(this.Request.Url.ToString());
            }
        }

        protected void Page_Load(object sender, EventArgs e) {
            // Delete post
            if (!string.IsNullOrWhiteSpace(Request.QueryString["delete"])) {
                // Authenticate request
                var postId = new Guid(Request.QueryString["delete"]);
                var post = this.DbContext.TopicPosts.SingleOrDefault(x => x.TopicPostId == postId && x.TopicId == this.TopicId);
                if (post == null) return; // Post not found
                if (post.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    // Own post
                    if (!post.Topic.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationDeleteOwn)) return; // Not authenticated
                }
                else {
                    // Other post
                    if (!post.Topic.EvaluateTopicPermissionsForCurrentUser(TopicAclEntry.OperationDeleteAll)) return; // Not authenticated
                }

                // Delete post
                this.DbContext.TopicPosts.Remove(post);
                this.DbContext.SaveChanges();

                // Redirect to self
                this.Response.Redirect(this.Request.Url.ToString());
            }
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e) {
            // Update TopicUserStatus
            var state = this.DbContext.TopicUserStates.SingleOrDefault(x => x.TopicId == this.TopicId && x.UserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase));
            if (state == null) {
                // First visit - create
                state = new TopicUserState {
                    TopicId = this.TopicId,
                    UserName = this.User.Identity.Name,
                    LastVisitDate = DateTime.UtcNow,
                    IsBookmarked = false
                };
                this.DbContext.TopicUserStates.Add(state);
            }
            else {
                // Subsequent visit - update
                state.LastVisitDate = DateTime.UtcNow;
            }
            this.DbContext.SaveChanges();
        }
    }
}